package net.sashag.nadlandroid;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.util.Log;

import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;
import com.googlecode.androidannotations.annotations.SystemService;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.api.Scope;

@EBean(scope = Scope.Singleton)
public class ProximityAlertManager {

	private static final String PROXIMITY_ALERT_ACTION = "net.sashag.nadlandroid.PROXIMITY_ALERT_ACTION";
	private static final float DEFAULT_PROX_ALERT_RADIUS = 200.0f; //in meters
	
	@SystemService protected LocationManager locationManager;
	@RootContext protected Context context;
	
	public boolean useProximityAlerts() {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
		return preferences.getBoolean("useProximityAlerts", true);
	}
	
	private PendingIntent getBroadcastPendingIntentForApartmentId(String apartmentId) {
		Intent intent = new Intent(PROXIMITY_ALERT_ACTION);
		intent.putExtra("ApartmentId", apartmentId);
		int requestCode = apartmentId.hashCode();
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		return pendingIntent;
	}
	
	@UiThread
	public void addProximityAlert(String apartmentId, double latitude, double longitude) {
		if (!useProximityAlerts())
			return;
		
		PendingIntent pendingIntent = getBroadcastPendingIntentForApartmentId(apartmentId);
		locationManager.addProximityAlert(
				latitude, longitude,
				DEFAULT_PROX_ALERT_RADIUS, -1, pendingIntent);
		Log.i("ProximityAlertManager", "Added proximity alert for apartment: " + apartmentId);
	}
	
	@UiThread
	public void removeProximityAlert(String apartmentId) {
		PendingIntent pendingIntent = getBroadcastPendingIntentForApartmentId(apartmentId);
		locationManager.removeProximityAlert(pendingIntent);
		Log.i("ProximityAlertManager", "Removed proximity alert for apartment: " + apartmentId);
	}
	
}
